package com.zhongkai.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.BoundBean;
import com.zhongkai.MessageTool;
import com.zhongkai.app.service.DeviceOperationService;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.listener.RocketMqProducer;
import com.zhongkai.model3.SetUnit;
import com.zhongkai.model3.SystemVersions;
import com.zhongkai.model3.UpdateRecord;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.Random;

@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceOperationServiceImpl implements DeviceOperationService {

    @Autowired
    private IBaseDao iBaseDao;

/*    @Autowired
    private JmsTemplate jmsTemplate;

    @Resource
    private Destination topicDestination;*/

    @Autowired
    private RocketMqProducer rocketMqProducer;
    /**
     * 添加新设备
     *
     * @param deviceID   设备uuid
     * @param device_IP  设备ip
     * @param set_status 设备状态 1 开机 2 关机 3离线
     * @param is_warning 是否报警  1 正常 2 报警
     * @param battery    总耗电量  取小数点后一位数 例如87.5
     * @param device_ver 版本号
     */
    @Override
    public void deviceAdd(
            String deviceID, //设备编号
            String device_IP,//设备ip
            String set_status,//设备状态 1 开机 2 关机 3离线
            String is_warning,////是否报警  1 正常 2 报警
            String battery,// 总耗电量


            String device_ver,//版本号
            String sim//设备卡卡号

    ) throws JsonProcessingException {

        if (StringUtils.isNullOrEmpty(deviceID) || StringUtils.isNullOrEmpty(device_IP) ||
                StringUtils.isNullOrEmpty(device_ver) || StringUtils.isNullOrEmpty(set_status) ||
                StringUtils.isNullOrEmpty(is_warning) || StringUtils.isNullOrEmpty(battery)

                ) {
            return;
        }


        SetUnit setUnit; //机组表

        setUnit = (SetUnit) iBaseDao.get("from SetUnit tb where tb.setUuid='" + deviceID + "'");
        SystemVersions versions1 = (SystemVersions) iBaseDao.get("from SystemVersions sp where sp.versions='" + device_ver + "'");



        DateTime dateTime = new DateTime();

        long millis = dateTime.getMillis(); //获取当前系统时间戳

       // String service = dateTime.withMillis(millis).toString("yyyy-MM-dd HH:mm:ss"); //系统时间
        /////////////////////////////////////////////////////////////


/*
        if (versions1 == null) {
         //   System.out.println("版本号不存在");

            BoundBean boundBean = new BoundBean();
            boundBean.setUnit_uuid(deviceID);
            boundBean.setUnit_ip(device_IP);
            boundBean.setIsBound("1");
      //      boundBean.setUserName("版本号不存在");
            boundBean.setUserPhone("null");
          //  boundBean.setServiceTime(service);

            ObjectMapper mapper = new ObjectMapper();
            final String json = "BoundBean:" + mapper.writeValueAsString(boundBean);


            jmsTemplate.send(topicDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {


                    TextMessage textMessage = session.createTextMessage(json);
                    return textMessage;
                }
            });

            return;
        }
*/


        /////////////////////////////////////////////////////////////////



        if (setUnit != null) { //设备存在 更改状态

            setUnit.setUpTime(millis); //设备上线时间
            setUnit.setSetIp(device_IP);//设备当前IP
            setUnit.setSetStatus(Integer.valueOf(set_status)); // 1开机 2关机 3离线
            setUnit.setWarning(Integer.valueOf(is_warning));//是否报警  1 正常 2 报警

            Float v = Float.valueOf(battery) * 10;
            Long batteryll = v.longValue();
            setUnit.setBattery(batteryll); //总耗电量

            setUnit.setSetSim(sim); //物联网卡卡号

            if (versions1 != null){
                setUnit.setVersions(versions1.getVersions());//设备版本号
                setUnit.setNumber(versions1.getId().intValue()); //版本号标识
            }else {
                setUnit.setVersions(device_ver);//设备版本号
                Random random = new Random();
                setUnit.setNumber(random.nextInt(10000));//设备版本号
            }





           // SetUnit
/*            iBaseDao.update1("update SetUnit unit set unit.upTime="+millis+" unit.setIp='"+device_IP+"' unit.setStatus="+
                    set_status+" unit.warning="+is_warning+" unit.battery="+batteryll+" unit.versions='"+versions1.getVersions()+"' unit.number="+versions1.getId());*/
         //   iBaseDao.update1();
            iBaseDao.update(setUnit);  //更新表数据

//----------------------------------------------------------------------------

            //跟netty通讯 向设备传递数据
            BoundBean boundBean = new BoundBean();
            boundBean.setUnit_uuid(deviceID);
            boundBean.setUnit_ip(device_IP);
            if ("1".equals(setUnit.getSetBound())) {
                boundBean.setIsBound("1");
         //       boundBean.setUserName("未绑定户主");

                //String hex = HexUtil.encodeHexStr("未绑定户主", CharsetUtil.CHARSET_UTF_8);
                boundBean.setUserPhone("null");
            } else {
                boundBean.setIsBound("2");
     //           boundBean.setUserName(setUnit.getUserName());
                boundBean.setUserPhone(setUnit.getUserPhone());
            }

          //  boundBean.setServiceTime(service);



             ObjectMapper mapper = new ObjectMapper();
             String json =   mapper.writeValueAsString(boundBean)+"&"+setUnit.getUserName()+"&"+setUnit.getSetAlias();
            try {
                byte[] bytes = json.getBytes("utf-8");
                rocketMqProducer.sendMsgIntime(MessageTool.BIG_SKY,MessageTool.UNIT_BOUND,bytes);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.out.println("转码失败");
                return;
            }

/*            jmsTemplate.send(topicDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {


                    TextMessage textMessage = session.createTextMessage(json);
                    return textMessage;
                }
            });*/


            return;

        } else {  //设备不存在增加新设备

            System.out.println("设备不存在增加新设备");
            setUnit = new SetUnit();

            setUnit.setSetUuid(deviceID);
            setUnit.setSetStatus(Integer.valueOf(set_status));
            setUnit.setSetTime(millis); //设备创建时间
            setUnit.setUpTime(millis); //设备上线时间
            setUnit.setSetIp(device_IP);//设备当前IP

            if (versions1 != null){
                setUnit.setVersions(versions1.getVersions());//设备版本号
                setUnit.setNumber(versions1.getId().intValue()); //版本号标识
            }else {
                setUnit.setVersions(device_ver);//设备版本号
                Random random = new Random();
                setUnit.setNumber(random.nextInt(10000));//设备版本号
            }

/*            setUnit.setVersions(versions1.getVersions());//设备版本号
            setUnit.setNumber(versions1.getId().intValue()); //版本号标识*/
            setUnit.setSetRemove("1"); //1为正常  2位删除
            //  setUnit.setWarning(1); //1正常  2异常
            setUnit.setTrusteeship("1"); //1为未托管  2为已托管
            setUnit.setSetBound("1");  //是否绑定业主  1 未绑定 2 已绑定
            setUnit.setRepair(1); //是否维修  1否 2正在维修
            setUnit.setSetSim(sim); //物联网卡卡号

            Float v = Float.valueOf(battery) * 10;
            Long batteryll = v.longValue();

            setUnit.setBattery(batteryll); //总耗电量

            setUnit.setWarning(Integer.valueOf(is_warning));//是否报警  1 正常 2 报警
            System.out.println("失败123");
            iBaseDao.save(setUnit);
            System.out.println("失败456");
            //跟netty通讯 向设备传递数据
            BoundBean boundBean = new BoundBean();
            boundBean.setUnit_uuid(deviceID);
            boundBean.setUnit_ip(device_IP);
            boundBean.setIsBound("1");
          //  boundBean.setUserName("未绑定户主");
            boundBean.setUserPhone("null");
        //    boundBean.setServiceTime(service);

            ObjectMapper mapper = new ObjectMapper();
            System.out.println("失败789");
            try {

                byte[] bytes = mapper.writeValueAsString(boundBean).getBytes("utf-8");
                rocketMqProducer.sendMsgIntime(MessageTool.BIG_SKY,MessageTool.UNIT_BOUND,bytes);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.out.println("失败100");
            }


/*
            jmsTemplate.send(topicDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {


                    TextMessage textMessage = session.createTextMessage(json);
                    return textMessage;
                }
            });*/

            return;
        }

    }

    @Override
    public void deviceDown(String device_IP) {
        if (StringUtils.isNullOrEmpty(device_IP)) {
            return;
        }
        //   iBaseDao.update1("update SetUnit su set su.setStatus=3 where su.setIp='" + device_IP + "'");
        //            iBaseDao.update1("update Anomaly su set su.state='3' where se.setCard='" + setUnit.getSetUuid() + "'");
       // SetUnit setUnit; //机组表

       // setUnit = (SetUnit) iBaseDao.get("from SetUnit tb where tb.setIp='" + device_IP + "'");

        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        iBaseDao.update1("update SetUnit unit set unit.setStatus=100 , unit.belowTime="+millis+" where unit.setIp='"+device_IP+"'");
/*        if (setUnit == null) {
            return;
        }*/



/*        Anomaly anomaly = (Anomaly) iBaseDao.get("from Anomaly se where se.setCard='" + setUnit.getSetUuid() + "'");
        if (anomaly != null) {
            anomaly.setState("3");
            iBaseDao.update(anomaly);
        }*/
    }

    @Override
    public void deviceDown2(String uuid) { //
/*        iBaseDao.update1("update SetUnit unit set unit.setStatus="+status+" , unit.battery="+v+" , unit.warning="+warning+" , unit.energy="+energy
                +" , unit.setIp='"+ip+"' where unit.setUuid='"+uuid+"'");*/
        //SetUnit

        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        iBaseDao.update1("update SetUnit unit set unit.setStatus=100 , unit.belowTime="+millis+" where unit.setUuid='"+uuid+"'");

/*        Anomaly anomaly = (Anomaly) iBaseDao.get("from Anomaly se where se.setCard='" + uuid + "'");
        if (anomaly != null) {
            anomaly.setState("3");
            iBaseDao.update(anomaly);
        }*/
    }

    @Override
    public void deviceUpdate(String loca, String uuid, String contrast) {
        if (
                StringUtils.isNullOrEmpty(loca) ||
                        StringUtils.isNullOrEmpty(uuid) ||
                        StringUtils.isNullOrEmpty(contrast)
                ) {

            return;
        }

        long millis = new DateTime().getMillis();


        UpdateRecord updateRecord = new UpdateRecord();

        updateRecord.setUnitUuid(uuid);
        updateRecord.setStatusCode(loca); //状态吗
        updateRecord.setRemark(contrast); //状态吗描述
        updateRecord.setUpdateTime(millis); //时间戳

        iBaseDao.save(updateRecord);
    }
}
